from django import http
from django.core.cache import cache
from django.views import View

from apps.areas.models import Area
from utils.response_code import RETCODE


class AreaView(View):
    def get (self,request):
        area_id=request.GET.get("area_id")
        if area_id is not None:

            sub_list=cache.get('sub_area_%s'%area_id)
            if sub_list is None:
                areas=Area.objects.filter(parent_id=area_id)
                sub_list=[]
                for area in areas:
                 sub_list.append({
                     'id':area.id,
                     'name':area.name
                 })


                 cache.set('sub_area_%s'%area_id,sub_list,24*3600)



            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok', 'sub_list': sub_list})

        else:
           pro_list=cache.get('prolist')
           if pro_list is None:
                areas=Area.objects.filter(parent=None)
                pro_list=[]
                for area in areas:
                    pro_list.append({
                        'id':area.id,
                        'name':area.name
                    })

                cache.set("pro_list", pro_list, 24*3600)
           return  http.JsonResponse({'code':RETCODE.OK,'errmsg':'ok','provinces':pro_list})

